﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Threading.Tasks;
using KC.DataAccess.Global;

namespace KC.Business.Scheduler
{
    public abstract class PluginBase : IDisposable
	{
		#region Properties
		protected DataRow drJob { get; private set; }
		protected string ConnStr { get; private set; }
		protected string LogFile { get; set; }
		public string Results { get; protected set; }
		public readonly string JobType;

		#endregion Properties

		public abstract void Dispose();
		public virtual void InitInner() { }
		protected abstract void RunInner();
		protected abstract void FailInner();
		protected abstract void CloseInner();
		
		public PluginBase() { }

		public void Init(DataRow drjob, string connStr)
		{
			drJob = drjob;
			ConnStr = connStr;
			LogFile = "";
			Results = "";
			InitInner();
		}

		public async void Run()
		{
			await SQL.ExecuteNonQuery(ConnStr, "update JobRuns set started=getdate, Result='Running', Details='' where id=" + drJob["ID"].ToString());
			RunInner();
		}

		public async void Fail()
		{
			await SQL.ExecuteNonQuery(ConnStr, "update JobRuns set ended=getdate, Result='Failed', Details='" + (Results ?? "").Replace("'", "''") + "' where id=" + drJob["ID"].ToString());
			FailInner();
		}

		public async void Close() 
		{
			await SQL.ExecuteNonQuery(ConnStr, "update JobRuns set ended=getdate, Result='Finished', Details='" + (Results ?? "").Replace("'", "''") + "' where id=" + drJob["ID"].ToString());
			CloseInner();
		}
	}
}
